package com.taobao.fanli.controller;

import com.taobao.fanli.common.RestResponse;
import com.taobao.fanli.dao.model.Order;
import com.taobao.fanli.service.LoginService;
import com.taobao.fanli.service.OrderService;
import com.taobao.fanli.service.OrderUserService;
import com.taobao.fanli.vo.Login;
import com.taobao.fanli.vo.UserOrderList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.UUID;

/**
 * @author:xiaolei
 * @date:2018/6/2
 */
@RestController
@RequestMapping(value = "/order")
@Api(value="订单接口api",description="订单接口api")
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Resource
    private OrderService orderService;
    @Resource
    private LoginService loginService;
    @Resource
    private OrderUserService orderUserService;

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    @ApiOperation(value="上传model，测试使用", notes="上传model，测试使用", httpMethod = "GET")
    public ModelAndView upload(){
        return new ModelAndView("upload");
    }

    @GetMapping("/info")
    @ApiOperation(value="订单详情", notes="订单详情", httpMethod = "GET")
    @ApiImplicitParam(name = "orderId", value = "订单id", required = true, dataType = "Integer", paramType = "query")
    public RestResponse orderInfo(
            @RequestParam(value = "orderId") Integer orderId,
            HttpServletRequest request,
            HttpServletResponse response
    ){
        Login login = loginService.getUserByCookie(request);
        if(login == null){
            return new RestResponse("用户没有登录", 305);
        }
        Order order = orderService.selectOrderInfo(orderId);
        return new RestResponse(order);
    }

    @RequestMapping(value = "/orderList", method = RequestMethod.GET)
    @ApiOperation(value="订单列表", notes="订单列表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderState", value = "订单状态", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "page", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "size", required = false, dataType = "Integer", paramType = "query")
    })
    public RestResponse orderList(
            @RequestParam(value = "orderState", required = false) String orderState,
            @RequestParam(value = "page") Integer page,
            @RequestParam(value = "size", required = false , defaultValue = "10") Integer size,
            HttpServletRequest request,
            HttpServletResponse response
    ){
        Login userByCookie = loginService.getUserByCookie(request);
        if(userByCookie == null){
            return new RestResponse("用户没有登录", 305);
        }
        UserOrderList userOrderList = orderUserService.getUserOrderList(userByCookie, orderState,
                page, size);
        return new RestResponse(userOrderList);
    }

    @RequestMapping(value = "/query", method = RequestMethod.GET)
    @ApiOperation(value="订单查询", notes="订单查询", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNumber", value = "订单编号", required = true, dataType = "Integer", paramType = "query")
    })
    public RestResponse query(
            @RequestParam(value = "orderNumber") String orderNumber,
            HttpServletRequest request,
            HttpServletResponse response
    ){
        Login login = loginService.getUserByCookie(request);
        if(login == null){
            return new RestResponse("用户没有登录", 305);
        }
        try {
            orderService.insertUserOrder(orderNumber, login);
            return new RestResponse("success");
        } catch (Exception e) {
            return new RestResponse(e.getMessage(), 505);
        }
    }

    @PostMapping("/userUpload")
    @ApiOperation(value="用户订单上传测试", notes="用户订单上传测试", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "file", required = true, dataType = "MultipartFile", paramType = "file")
    })
    public RestResponse userFileUpload(
            @RequestParam("file") MultipartFile multipartFile,
            HttpServletRequest request) {
        Login userByCookie = loginService.getUserByCookie(request);
        if(userByCookie == null){
            return new RestResponse("用户没有登录", 305);
        }
        if (multipartFile.isEmpty()) {
            return new RestResponse("文件为空", 505);
        }
        String fileType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        if (fileType.equals(".xlsx") || fileType.equals(".xls")) {
            String base = request.getSession().getServletContext().getRealPath("/") + "attachments" + File.separator + UUID.randomUUID().toString().replace("-","");//设置文件上传位置
            File file = new File(base);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                String path = base + File.separator + multipartFile.getOriginalFilename();
                multipartFile.transferTo(new File(path));
                //上传成功后读取Excel表格里面的数据
                orderService.insertUserOrderData(path, userByCookie);
                file.delete();
            } catch (Exception e) {
                return new RestResponse("excel数据导入格式不正确", 505);
            }
            return new RestResponse("success");
        } else {
            return new RestResponse("文件不是excel", 505);
        }
    }

    @PostMapping("/upload")
    @ApiOperation(value="后台订单上传", notes="后台订单上传", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "file", required = true, dataType = "MultipartFile", paramType = "file")
    })
    public RestResponse fileUpload(
            @RequestParam("file") MultipartFile multipartFile,
            HttpServletRequest request) {
        if (multipartFile.isEmpty()) {
            return new RestResponse("文件为空", 505);
        }
        String fileType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        if (fileType.equals(".xlsx") || fileType.equals(".xls")) {
            String base = request.getSession().getServletContext().getRealPath("/") + "attachments" + File.separator + UUID.randomUUID().toString().replace("-","");//设置文件上传位置
            File file = new File(base);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                String path = base + File.separator + multipartFile.getOriginalFilename();
                multipartFile.transferTo(new File(path));
                //上传成功后读取Excel表格里面的数据
                orderService.insertOrderData(path);
                file.delete();
            } catch (Exception e) {
                logger.error("excel数据导入失败:",e);
                return new RestResponse("excel数据导入格式不正确", 505);
            }
            return new RestResponse("success");
        } else {
            return new RestResponse("文件不是excel", 505);
        }
    }
}
